package com.ciwong.epaper.modules.me.dao;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.MCToken;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.me.bean.ClassMember;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.IntegralsBean;
import com.ciwong.epaper.modules.me.bean.MedalsBean;
import com.ciwong.epaper.modules.me.bean.Service;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.bean.ServiceInfo;
import com.ciwong.epaper.modules.me.bean.UserPointMedalsBean;
import com.ciwong.epaper.modules.me.dao.db.db.StudyRecordDB;
import com.ciwong.epaper.modules.me.presenter.GetPointContral;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.toast.ToastCustomView;

import java.io.IOException;
import java.io.Serializable;
import java.security.cert.TrustAnchor;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

/**
 * 我 相关业务Dao
 *
 * @author bin
 * @version ciwong v.1.0 2015/7/23 20:08
 * @since ciwong v.1.0
 */
public class MeDao {
    private static MeDao instance;

    private MeDao() {
    }

    /**
     * 获取唯一实例
     *
     * @return 唯一实例
     */
    public static MeDao getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    /**
     * 实例化对象
     */
    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new MeDao();
        }
    }

    /**
     * 注册用户
     *
     * @param business_id
     * @param sex
     * @param password
     * @param callBack
     */
    public void registerUser(String business_id, String mobile, String verify_code, String username, String sex, String password, String confirmPassword,
                             final BaseCallBack callBack) {
        MeRequest.registerUser(business_id, mobile, verify_code, username, sex, password, confirmPassword, callBack);
    }

    /**
     * 刷新token
     *
     * @param rfToken 刷新token
     */
    public void updateUserToken(String rfToken, BaseCallBack callBack) {
        MeRequest.updateToken(rfToken, callBack);
    }

    //意见反馈接口
    public void getIssued(Context context, String contrnt, String userName, String mobile, BaseExtCallBack callBack) {
        MeRequest.getIssued(context, contrnt, userName, mobile, callBack);
    }

    public void getDuibaLoginurl(final BaseCallBack callBack, String userId) {
        MeRequest.getDuibaLoginurl(callBack, userId);
    }


    /**
     * 登陆获取用户TOKEN
     *
     * @param application EApplication
     * @param userId      用户ID
     * @param password    用户密码
     * @param callBack    回调
     */
    public void getUserToken(EApplication application, String userId, String password, String uuid, String captchaCode, BaseCallBack callBack) {
        MeRequest.getUserToken(application, userId, password, uuid, captchaCode, callBack);

    }

    public void getUserIdByPhone(int brandId, String mobile, final BaseCallBack callBack) {
        MeRequest.getUserIdByPhone(brandId, mobile, callBack);

    }

    /**
     * 判断绑定手机号
     */
    public void getBindInfo(final EApplication application, final String business_id, final String userId, final BaseCallBack callBack) {
        MeRequest.getBindInfo(business_id, userId, callBack);
    }

//    /**
//     * 微信通过CODE获取TOKEN
//     *
//     * @param application EApplication
//     * @param brandId     品牌ID
//     * @param appid       第三方开发者平台分配的APPID（必选)
//     * @param code        第三方登录授权返回的code（必选)
//     * @param svrtype     第三方服务的类型,见附表1.2（QQ、weixin）（必选)
//     * @param clientID    clientID
//     * @param flag        1 返回习网token， 2 返回第三方token，3 两个都返回（不填默认为1）（可选)
//     * @param callBack
//     */
//    public void getTokenByCode(final String phoneNumber, final EApplication application,
//                               final int brandId, String appid, String code, String svrtype,
//                               int flag, final String clientID, final BaseCallBack callBack) {
//        WorkBookRequest.getTokenByCode(appid, code, svrtype, flag, new BaseCallBack() {
//            @Override
//            public void failed(int errorCode, Object data) {
//                callBack.failed(errorCode, data);
//            }
//
//            @Override
//            public void failed(Object data) {
//                callBack.failed(data);
//            }
//
//            @Override
//            public void success(Object data) {
//                LoginTokenInfo loginTokenInfo = (LoginTokenInfo) data;
//                setVerifyInfo(loginTokenInfo.getToken(), clientID);
//                getUserInfoBase(phoneNumber, false, application, brandId,
//                        LoginTokenInfo.LoginType.LOGIN_TYPE_WEIXIN, null,
//                        callBack);
//            }
//        });
//    }

//    /**
//     * (三)QQ 通过第三方openid获取习网token
//     *
//     * @param application   EApplication
//     * @param brandId       品牌ID
//     * @param appid         第三方开发者平台分配的APPID（必选)
//     * @param openid        授权用户唯一标识（必选)
//     * @param access_token  接口调用凭证（必选)
//     * @param expires_in    access_token接口调用凭证超时时间，单位（秒）（必选)
//     * @param refresh_token （可选)
//     * @param svrtype       第三方服务的类型,见附表1.2（QQ、weixin），默认为QQ（可选)
//     * @param clientID      客户端ID
//     * @param callBack
//     */
//    public void getTokenByOpenId(final String phoneNumber, final EApplication application,
//                                 final int brandId, String appid, String openid, String access_token,
//                                 String expires_in, String refresh_token, String svrtype,
//                                 final String clientID, final BaseCallBack callBack) {
//        WorkBookRequest.getTokenByOpenId(appid, openid, access_token, expires_in,
//                refresh_token, svrtype, new BaseCallBack() {
//                    @Override
//                    public void failed(int errorCode, Object data) {
//                        callBack.failed(errorCode, data);
//                    }
//
//                    @Override
//                    public void failed(Object data) {
//                        callBack.failed(data);
//                    }
//
//                    @Override
//                    public void success(Object data) {
//                        LoginTokenInfo loginTokenInfo = (LoginTokenInfo) data;
//                        setVerifyInfo(loginTokenInfo.getToken(), clientID);
//                        getUserInfoBase(phoneNumber, false, application, brandId,
//                                LoginTokenInfo.LoginType.LOGIN_TYPE_QQ, null,
//                                callBack);
//                    }
//                });
//    }

    /**
     * 设置验证信息
     *
     * @param info     验证信息
     * @param clientID
     */
    public void setVerifyInfo(MCToken info, String clientID) {
        BaseRequest.VerifyInfo verifyInfo = new BaseRequest.VerifyInfo();
        verifyInfo.setAccessToken(info.getAccessToken());
        verifyInfo.setClientId(clientID);
        verifyInfo.setClientIp(DeviceUtils.getLocalIpAddress());
        verifyInfo.setOauthVersion("2.0");
        verifyInfo.setScope("all");
        verifyInfo.setTokenType(info.getTokenType());
        verifyInfo.setRefreshToken(info.getRefreshToken());
        verifyInfo.setExpiresIn(info.getExpiresIn() + "");
        verifyInfo.setOpenId(info.getOpenId());
        verifyInfo.setTermType(5);
        try {
            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                    verifyInfo);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpRequest.setVerifyInfo(verifyInfo);
            CWLog.e("debug", "verifyInfo: " + verifyInfo);
        }
    }

    /**
     * 获取电子报品牌信息
     *
     * @param application NApplication
     * @param userId      用户ID
     * @param callBack    回调
     */
    public void getNewspaperBrand(final EApplication application,
                                  final long userId, final BaseCallBack callBack) {
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_SERVICE,
                new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        callBack.success();
                    }

                    @Override
                    public void failed(Object data) {
                    }

                    @Override
                    public void success(Object data) {
                        Service service = (Service) data;
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_SERVICE,
                                service);
                        callBack.success();
                    }
                });
    }

    /**
     * 习网服务试用
     *
     * @param userId        用户ID
     * @param serviceTypeId 服务类型ID(25-阳光英语报服务)
     * @param versionType   服务版本（1:个人版 2:班级版 3:学校版）
     * @param num           申请试用天数，最多不可以超过15天
     * @param callBack      回调
     */
    public String openExperiment(long userId, int serviceTypeId, int versionType,
                                 int num, BaseCallBack callBack) {

        return MeRequest.openExperiment(userId, serviceTypeId, versionType, num, EpaperConstant.TYPE_ID_OF_MOBILE,
                callBack);

    }

    /**
     * 判断是否有家长绑定
     *
     * @param userId   用户ID
     * @param callBack 回调
     */
    public String getMyParent(long userId, BaseCallBack callBack) {
        return MeRequest.getMyParent(userId, callBack);
    }

    /**
     * 判断是否有家长绑定
     *
     * @param userId   用户ID
     * @param callBack 回调
     */
    public String sendBuyService(long userId, int serviceId, String serviceName, float price, int unit, final BaseCallBack callBack) {
        return MeRequest.sendBuyService(userId, serviceId, serviceName, price, unit, callBack);
    }

    /**
     * 获取服务开通状态详情列表
     * 修改于书柜重构BY young 2016/09/11
     *
     * @param application   EApplication
     * @param brandId       品牌ID
     * @param userId        用户ID
     * @param serviceTypeId 服务类型ID(0：全部)
     * @param callBack      回调
     */
    public String getServiceDetails(final EApplication application, int brandId,
                                    final long userId, final int serviceTypeId,
                                    final BaseCallBack callBack) {

        return MeRequest.serviceState(brandId, userId, serviceTypeId,
                new BaseCallBack() {
                    @Override
                    public void failed(Object data) {
                        callBack.failed(data);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        callBack.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data) {
                        List<ServiceInfo> serviceInfos = (List<ServiceInfo>) data;
                        //此时服务列表 已经是最新的服务列表并且已经是与本地服务列表比对过 的服务列表  并且选中状态也是本地为准
                        List<ServiceDetail> serviceDetails = null;
                        for (ServiceInfo serviceInfo : serviceInfos) {
                            if (userId == serviceInfo.getUserId()) {
                                serviceDetails = serviceInfo.getService();
                                break;
                            }
                        }
                        //young
                        getLocalServiceDetails(application, serviceDetails,
                                callBack);
                    }
                });
    }


    /**
     * 获取服务开通状态详情列表
     * 修改于书柜重构BY young 2016/09/11
     *
     * @param brandId  品牌ID
     * @param callBack 回调
     */
    public void getSubjectListByGrade(int brandId, int gradeId, int salesType,
                                      final BaseCallBack callBack) {
        MeRequest.getSubjectListByGrade(brandId, gradeId, salesType, callBack);

    }


    /**
     * 获取本地服务详情列表(对比本地数据)
     *
     * @param application
     * @param serviceDetails
     * @param callBack
     */
    private void getLocalServiceDetails(final EApplication application,
                                        final List<ServiceDetail> serviceDetails,
                                        final BaseCallBack callBack) {
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                new BaseCallBack() {

                    @Override
                    public void success(Object data) {
                        List<ServiceDetail> localDetailList = (List<ServiceDetail>) data;
                        for (ServiceDetail serviceDetail : serviceDetails) {
                            //localDetailList不为空时时才同步状态
                            if (localDetailList != null) {
                                int index = localDetailList.indexOf(serviceDetail);
                                if (index != -1 && index < localDetailList.size()) {
                                    ServiceDetail localDetail = localDetailList.get(index);
                                    //服务过期,本地为准.服务未过期，默认值为NO
                                    if (serviceDetail.isbExpired()) {//服务过期  是否删除以本地为准
                                        serviceDetail.setDeleted(localDetail.isDeleted());// isDeleted字段以本地数据为准
                                        //修改服务选中状态  以本地位准
                                        serviceDetail.setSelect(localDetail.isSelect());
                                        //修改本地买断状态和本地相同
                                        serviceDetail.setSign(localDetail.getSign());
                                    } else {//服务未过期 不可删除
                                        serviceDetail.setSelect(localDetail.isSelect());
                                        //修改本地买断状态和本地相同
                                        serviceDetail.setSign(localDetail.getSign());
                                    }
                                }
                            }
                        }

                        application.setServiceDetails(serviceDetails);
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                                (Serializable) serviceDetails);
                        //setAddBookServiceDetails(application,serviceDetails,callBack);
                        getServiceDetail(application, serviceDetails, callBack);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        application.setServiceDetails(serviceDetails);
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                                (Serializable) serviceDetails);
                        //setAddBookServiceDetails(application,serviceDetails,callBack);
                        getServiceDetail(application, serviceDetails, callBack);
                    }

                    @Override
                    public void failed(Object data) {
                        application.setServiceDetails(serviceDetails);
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                                (Serializable) serviceDetails);
                        //setAddBookServiceDetails(application,serviceDetails,callBack);
                        getServiceDetail(application, serviceDetails, callBack);
                    }
                });
    }

    /**
     * AddBookActivity服务列表
     *
     * @param serviceDetails 经过与本地比对，已本地为准的服务列表
     */
    private void setAddBookServiceDetails(final EApplication application, final List<ServiceDetail> serviceDetails, final BaseCallBack callBack) {

        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_EXIST_LIST, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

                SerializableManager.getInstance().serialize(
                        SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_EXIST_LIST, (Serializable) serviceDetails);
                getServiceDetail(application, serviceDetails, callBack);
            }

            @Override
            public void failed(Object data) {
                SerializableManager.getInstance().serialize(
                        SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_EXIST_LIST, (Serializable) serviceDetails);
                getServiceDetail(application, serviceDetails, callBack);
            }

            @Override
            public void success(Object data) {
                List<ServiceDetail> localAddServiceDetails = (List<ServiceDetail>) data;
                List<ServiceDetail> newServiceDetails = new ArrayList<ServiceDetail>();
                for (ServiceDetail serviceDetail : serviceDetails) {

                    if (!serviceDetail.isDeleted()) {
                        newServiceDetails.add(serviceDetail);
                    }
                }
                //如果有新加入的服务条目时，添加到本地列表中

                for (ServiceDetail serviceDetail : newServiceDetails) {
                    int index = localAddServiceDetails.indexOf(serviceDetail);
                    if (index != -1) {
                        ServiceDetail localDetail = localAddServiceDetails
                                .get(index);
                        serviceDetail.setSelect(localDetail.isSelect());
                    }
                }
                SerializableManager.getInstance().serialize(
                        SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_EXIST_LIST, (Serializable) newServiceDetails);

                getServiceDetail(application, serviceDetails, callBack);
            }

        });

    }

    /**
     * 获取默认服务开通状态详情
     *
     * @param application    NApplication
     * @param serviceDetails 服务开通状态详情列表
     * @param callBack       回调
     */
    private void getServiceDetail(final EApplication application,
                                  final List<ServiceDetail> serviceDetails,
                                  final BaseCallBack callBack) {
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL,
                new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        ServiceDetail serviceDetail = null;
                        if (serviceDetails != null) {
                            for (ServiceDetail sd : serviceDetails) {
                                if (!sd.isDeleted()) {
                                    serviceDetail = sd;
                                    break;
                                }
                            }
                        }
                        application.setServiceDetail(serviceDetail);
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL,
                                serviceDetail);
                        //判断是否绑定手机号
                        //getBindInfo(application,"1",callBack);
                        callBack.success(serviceDetails);
                    }


                    @Override
                    public void failed(Object data) {
                        callBack.success(serviceDetails);
                    }

                    @Override
                    public void success(Object data) {
                        ServiceDetail serviceDetail = null;
                        if (serviceDetails != null && !serviceDetails.isEmpty()) {
                            int indexOf = serviceDetails.indexOf(data);
                            if (indexOf == -1) {
                                for (ServiceDetail sd : serviceDetails) {
                                    if (!sd.isDeleted()) {
                                        serviceDetail = sd;
                                        break;
                                    }
                                }
                            } else {
                                serviceDetail = serviceDetails.get(indexOf);
                            }
                        }
                        application.setServiceDetail(serviceDetail);
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL,
                                serviceDetail);
                        //判断是否绑定手机号
                        // getBindInfo(application,"1",callBack);
                        callBack.success(serviceDetails);
                    }
                });
    }

//
//    /**
//     * 获取用户信息
//     *
//     * @param application EApplication
//     * @param brandId     品牌ID
//     * @param loginType   登录类型
//     * @param password    密码
//     * @param callBack    回调
//     */
//    public void getUserInfoBase(final String phoneNumber, final Boolean boo, final EApplication application,
//                                final int brandId, final int loginType, final String password,
//                                final BaseCallBack callBack,String userId) {
//        WorkBookRequest.getUserInfoBase(new BaseCallBack() {
//            @Override
//            public void failed(int errorCode, Object data) {
//                callBack.failed(errorCode, data);
//            }
//
//            @Override
//            public void failed(Object data) {
//                callBack.failed(data);
//            }
//
//            @Override
//            public void success(Object data) {
//                UserInfoBase userInfoBase = (UserInfoBase) data;
//                try {
//                    application.setUserInfoBase(userInfoBase);
//                    CWSys.setSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER,
//                            userInfoBase.getUserId());
//                    CWSys.setSharedInt(EConstants.SHARE_KEY_AUTO_LOGIN_TYPE,
//                            loginType);
//                    CWSys.setSharedSerializable(
//                            BaseConstants.SHARE_KEY_USER_INFO_BASE,
//                            userInfoBase);
//                    final NewLoginAccountInfo loginAccountInfo = new NewLoginAccountInfo();
//                    loginAccountInfo.setUserId(userInfoBase.getUserId());
//                    loginAccountInfo.setUserPwd(password);
//                    loginAccountInfo.setAvatar(userInfoBase.getAvatar());
//                    loginAccountInfo.setPhonelogin(boo);
//                    if (boo) {
//                        loginAccountInfo.setPhoneNumber(phoneNumber);
//                    }
//
//
//                    SerializableManager.getInstance().deSerialize(
//                            SerializableManager.SerializeKey.SHARE_KEY_LOGIN_ACCOUNT_LIST,
//                            new BaseCallBack() {
//                                @Override
//                                public void failed(int errorCode, Object data) {
//                                    List<NewLoginAccountInfo> loginAccountInfos = new ArrayList<NewLoginAccountInfo>();
//                                    loginAccountInfos.add(loginAccountInfo);
//                                    SerializableManager.getInstance().serialize(
//                                            SerializableManager.SerializeKey.SHARE_KEY_LOGIN_ACCOUNT_LIST,
//                                            (Serializable) loginAccountInfos,
//                                            false);
//
//                                if(loginAccountInfos==null){
//                                    return;
//                                }
//                                    //存入新的用户登录结构数据
//                                    List<UserAccountInfo> userAccountInfoList=new ArrayList<UserAccountInfo>();
//                                    for (NewLoginAccountInfo loginAccountInfo:loginAccountInfos){
//                                        UserAccountInfo userAccountInfo=new UserAccountInfo();
//                                        userAccountInfo.setUserId(loginAccountInfo.getUserId());
//                                        userAccountInfo.setAvatar(loginAccountInfo.getAvatar());
//                                        userAccountInfo.setUserPwd(loginAccountInfo.getUserPwd());
//                                        userAccountInfo.setPhonelogin(loginAccountInfo.getPhonelogin());
//                                        userAccountInfo.setPhoneNumber(loginAccountInfo.getPhoneNumber());
//                                        userAccountInfoList.add(userAccountInfo);
//                                    }
//                                    SerializableManager.getInstance().serialize(
//                                            SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
//                                            (Serializable) userAccountInfoList, false);
//                                }
//
//                                @Override
//                                public void failed(Object data) {
//
//                                }
//
//                                @Override
//                                public void success(Object data) {
////                                    List<NewLoginAccountInfo> loginAccountInfos=null;
//                                    List<NewLoginAccountInfo> newLoginAccountInfoList  = new ArrayList<NewLoginAccountInfo>();
//                                    List<LoginAccountInfo>  loginAccountInfos= (List<LoginAccountInfo>) data;
//                                    if (null != loginAccountInfos && loginAccountInfos.size() > 0) {
//                                        for (LoginAccountInfo baseBean : loginAccountInfos) {
//                                            if (baseBean instanceof NewLoginAccountInfo) {
//                                                Log.d("logindata", "######NewLoginAccountInfo########");
//                                                newLoginAccountInfoList.add((NewLoginAccountInfo)baseBean);
//                                            } else if (baseBean instanceof LoginAccountInfo) {
//                                                Log.d("logindata", "######LoginAccountInfo########");
//                                                NewLoginAccountInfo loginAccountInfo = new NewLoginAccountInfo();
//                                                loginAccountInfo.setUserId(baseBean.getUserId());
//                                                loginAccountInfo.setUserPwd(baseBean.getUserPwd());
//                                                loginAccountInfo.setAvatar(baseBean.getAvatar());
//                                                loginAccountInfo.setPhonelogin(false);
//                                                loginAccountInfo.setPhoneNumber("");
//                                                newLoginAccountInfoList.add(loginAccountInfo);
//                                            }
//                                        }
//                                    }
//
//
//
////                                    if(data instanceof LoginAccountInfo){
////                                        List<LoginAccountInfo> oldloginAccountInfos= (List<LoginAccountInfo> ) data;
////                                        for (LoginAccountInfo loginAccountInfo:oldloginAccountInfos
////                                                ) {
////                                            NewLoginAccountInfo newLoginAccountInfo=new NewLoginAccountInfo();
////                                            newLoginAccountInfo.setUserId(loginAccountInfo.getUserId());
////                                            newLoginAccountInfo.setUserPwd(loginAccountInfo.getUserPwd());
////                                            newLoginAccountInfo.setAvatar(loginAccountInfo.getAvatar());
////                                            loginAccountInfos.add(newLoginAccountInfo);
////                                        }
////
////                                    }else if(data instanceof NewLoginAccountInfo){
////                                        loginAccountInfos = (List<NewLoginAccountInfo>) data;
////                                    }
//
//
//                                  //  List<NewLoginAccountInfo> loginAccountInfos = (List<NewLoginAccountInfo>) data;
//                                    int indexOf = newLoginAccountInfoList
//                                            .indexOf(loginAccountInfo);
//
//                                    if (indexOf >= 0) {
//                                        newLoginAccountInfoList.remove(indexOf);
//                                    }
//
//                                    newLoginAccountInfoList.add(0,loginAccountInfo);
////                                    loginAccountInfos.add(0, loginAccountInfo);
//
//                                    SerializableManager.getInstance().serialize(
//                                            SerializableManager.SerializeKey.SHARE_KEY_LOGIN_ACCOUNT_LIST,
//                                            (Serializable) newLoginAccountInfoList,
//                                            false);
//                                    if(newLoginAccountInfoList==null){
//                                        return;
//                                    }
//
//                                    //存入新的用户登录结构数据
//                                    List<UserAccountInfo> userAccountInfoList=new ArrayList<UserAccountInfo>();
//                                    for (NewLoginAccountInfo loginAccountInfo:newLoginAccountInfoList){
//                                        UserAccountInfo userAccountInfo=new UserAccountInfo();
//                                        userAccountInfo.setUserId(loginAccountInfo.getUserId());
//                                        userAccountInfo.setAvatar(loginAccountInfo.getAvatar());
//                                        userAccountInfo.setUserPwd(loginAccountInfo.getUserPwd());
//                                        userAccountInfo.setPhonelogin(loginAccountInfo.getPhonelogin());
//                                        userAccountInfo.setPhoneNumber(loginAccountInfo.getPhoneNumber());
//                                        userAccountInfoList.add(userAccountInfo);
//                                    }
//                                    SerializableManager.getInstance().serialize(
//                                            SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
//                                            (Serializable) userAccountInfoList, false);
//
//
//
//
//
//
//
//
//                                }
//                            }, false);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    callBack.failed(e);
//                } finally {
//                    // getNewspaperBrand(application, userInfoBase, callBack);
//                    getServiceDetails(application, brandId,
//                            userInfoBase.getUserId(), 0, callBack);
//                }
//            }
//        },userId);
//    }

    /**
     * 获取用户学校信息
     *
     * @param callBack 回调函数
     */
    public void getSchoolInfo(BaseCallBack callBack) {
        MeRequest.getSchoolInfo(callBack);
    }

    /**
     * 获取用户学校信息
     *
     * @param callBack 回调函数
     */
    public void getUserInfoBase(String userId, BaseCallBack callBack) {
        MeRequest.getUserInfoBase(callBack, userId);
    }

    /**
     * 获取当前登录用户信息，并返回所在学校和班级信息
     *
     * @param callBack 回调函数
     */
    public void getDetailUserInfo(BaseCallBack callBack) {
        MeRequest.getDetailUserInfo(callBack);
    }

    /**
     * 获取网络我提交的作业列表
     *
     * @param brandId  品牌ID
     * @param isOnline 是否线上作业 1:是 0:否
     * @param page     页码
     * @param pageSize 每页条数
     * @param callBack 回调
     */
    public void getMyStudyRecord(int brandId, int isOnline, int page,
                                 int pageSize, BaseCallBack callBack) {
        MeRequest.getMyStudyRecord(brandId, isOnline, page, pageSize, callBack);
    }

    /**
     * 获取听说模考批改结果
     *
     * @param doWorkId 学生做作业ID
     * @param callBack 回调
     */
    public void getListenWorkCorrect(final String doWorkId,
                                     final BaseCallBack callBack) {
        MeRequest.getListenWorkCorrect(doWorkId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                callBack.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                callBack.failed(data);
            }

            @Override
            public void success(Object data) {
                SerializableManager.getInstance().serialize(
                        SerializableManager.SerializeKey.SHARE_KEY_LISTEN_SPEAK_WORK_CORRECT_ANSWER
                                + doWorkId,
                        String.valueOf(data));
                callBack.success(data);
            }
        });
    }

    /**
     * 查询所有的作业数据
     *
     * @param isOnline 是否是线上作业
     * @param callBack 回调
     */
    public void queryMyStudyRecord(final int isOnline,
                                   final BaseCallBack callBack) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                final List<Answer> answers = StudyRecordDB
                        .queryAllWorkList(isOnline);
                if (callBack != null) {
                    callBack.success(answers);
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 获取不同模块作业提交情况统计
     *
     * @param brandId   品牌ID
     * @param moduleIds 模块ID集合
     * @param callBack  回调
     */
    public void getDoWorkReport(int brandId, String moduleIds,
                                final BaseCallBack callBack) {
        MeRequest.getDoWorkReport(brandId, moduleIds, callBack);
    }

    /**
     * 修改用户信息
     *
     * @param avatar   头像地址
     * @param callBack BaseCallBack
     */
    public void updateUserInfo(String avatar, BaseCallBack callBack) {
        MeRequest.updateUserInfo(avatar, callBack);
    }


    /**
     * 修改用户信息
     *
     * @param
     * @param callBack BaseCallBack
     */
    public void updateUserBgInfo(String bgUrl, boolean isGet, BaseCallBack callBack) {
        MeRequest.updateUserBgInfo(bgUrl, isGet, callBack);
    }

    /**
     * 根据邀请码加入班级
     *
     * @param brandId   品牌ID
     * @param applyCode 邀请码
     * @param callBack  BaseCallBack
     */
    public void joinClassByApplyCode(int brandId, String applyCode,
                                     final BaseCallBack callBack) {
        MeRequest.joinClassByApplyCode(brandId, applyCode, callBack);
    }

    /**
     * 获取班级列表
     *
     * @param brandId  品牌ID
     * @param callBack 回调
     */
    public void getClassList(int brandId, int userRole, int schoolId, final BaseCallBack callBack) {
        MeRequest.getClassList(brandId, userRole, schoolId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                callBack.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                callBack.failed(data);
            }

            @Override
            public void success(Object data) {
                List<Clazz> clazzs = (List<Clazz>) data;
                MeUtil.filterClass(clazzs);
                callBack.success(clazzs);
            }
        });
    }


    /**
     * 根据老师手机号码获取班级列表
     *
     * @param brandId  品牌ID
     * @param callBack 回调
     */
    public void getClassListByTeacherPhoneNum(int brandId, String phoneNum, final BaseCallBack callBack) {
        MeRequest.getClassListByTeacherPhoneNum(brandId, phoneNum, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                callBack.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                callBack.failed(data);
            }

            @Override
            public void success(Object data) {
                List<Clazz> clazzs = (List<Clazz>) data;
                callBack.success(clazzs);
            }
        });
    }


    /**
     * 加入更换班级，加入的班级from id 为0
     *
     * @param brandId  品牌ID
     * @param callBack 回调
     */
    public void joinClassById(int brandId, int role, long from_id, long to_id, final BaseCallBack callBack) {
        MeRequest.joinClassById(brandId, role, from_id, to_id, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                callBack.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                callBack.failed(data);
            }

            @Override
            public void success(Object data) {
                callBack.success(data);
            }
        });
    }


    /**
     * @param brandId  品牌id
     * @param _cId     班级id
     * @param flag     默认为1,是否需要返回头像、职务和角色:0,false|1,true
     * @param role     查询用户角色
     *                 详见附表 1.5
     * @param callBack
     */
    public void getClassMember(int brandId, long _cId, int flag, int role, final BaseCallBack callBack) {
        MeRequest.getClassMembers(brandId, _cId, flag, role, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                callBack.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                callBack.failed(data);
            }

            @Override
            public void success(Object data) {
                List<ClassMember> users = (List<ClassMember>) data;
                callBack.success(users);
            }
        });
    }


    /**
     * 获取班级详情
     *
     * @param brandId  品牌ID
     * @param callBack 回调
     */
    public void getClassDetail(int brandId, long _cId, final BaseCallBack callBack) {
        MeRequest.getClassDetail(brandId, _cId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                callBack.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                callBack.failed(data);
            }

            @Override
            public void success(Object data) {
                Clazz clazz = (Clazz) data;
//                MeUtil.filterClass(clazz);
                callBack.success(clazz);
            }
        });
    }

    /**
     * 绑定手机号
     *
     * @param userId
     * @param business_id
     * @param mobile
     * @param verify_code
     * @param callBack
     */

    public void BindPhone(String userId, String business_id, String mobile, String verify_code, final BaseCallBack callBack) {
        final String mobileEncrypt = AESCBCUtil.encrypt(mobile, AESCBCUtil.AESCBC_HEX);
        MeRequest.BindPhone(userId, business_id, mobileEncrypt, verify_code, callBack);
    }

    /**
     * 重置密码接口
     *
     * @param business_id
     * @param mobile
     * @param verify_code
     * @param password
     * @param confirmPassword
     * @param callBack
     */
    public void reSetPSW(String business_id, String mobile, String verify_code, String password, String confirmPassword, final BaseCallBack callBack) {
        MeRequest.reSetPSW(business_id, mobile, verify_code, password, confirmPassword, callBack);
    }

    /**
     * 校验验证码是否正确
     *
     * @param business_id
     * @param mobile
     * @param callBack
     */
    public void ValidSmsVerityCode(String business_id, String mobile, String verify_code, final BaseCallBack callBack) {
        MeRequest.ValidSmsVerityCode(business_id, mobile, verify_code, callBack);
    }

    /**
     * 获取绑定手机号验证码
     *
     * @param
     * @param callBack
     */
    public void getSmsVerityCode(String business_id, String mobile, String uuid, String captchaCode,String template_id, final BaseCallBack callBack) {
        MeRequest.getSmsVerityCode(business_id, mobile, uuid, captchaCode, template_id, callBack);
    }


    /**
     * 根据邀请码获取班级信息
     *
     * @param brandId   品牌ID
     * @param applyCode 邀请码
     * @param callBack  回调
     */
    public void getClassInfoByApplyCode(int brandId, String applyCode,
                                        final BaseCallBack callBack) {
        MeRequest.getClassInfoByApplyCode(brandId, applyCode, callBack);
    }

    /**
     * 获取我的错题
     *
     * @param doWorkId
     * @param callBack
     */
    public void getMyWrongQuestion(String doWorkId, BaseCallBack callBack) {
        MeRequest.getMyWrongQuestion(doWorkId, callBack);
    }

    /**
     * 验证密码
     *
     * @param pwd      密码
     * @param callBack 回调
     */
    public void verifyPossword(String pwd, BaseCallBack callBack) {
        MeRequest.verifyPossword(pwd, callBack);
    }

    /**
     * 修改密码
     *
     * @param currentPwd 当前密码
     * @param newPwd     新密码
     * @param callBack   回调
     */
    public String modifyPossword(String currentPwd, String newPwd,
                                 BaseCallBack callBack) {
        return MeRequest.modifyPossword(currentPwd, newPwd, callBack);
    }

    /**
     * 获取电子报品牌信息列表
     *
     * @param brandId   品牌ID
     * @param serviceId 服务ID
     * @param callBack  回调
     */
    public String getServices(int brandId, int serviceId,
                              final BaseCallBack callBack) {
        return MeRequest.getServices(brandId, serviceId, callBack);
    }

    /**
     * 获取服务类型及价格
     *
     * @param sTypeId     服务类型 （25：阳光英语报）
     * @param versionType 服务版本（1：Android 2: IOS 0:其它）
     * @param callBack    回调
     */
    public void getServicePirce(int sTypeId, int versionType,
                                final BaseCallBack callBack) {
        MeRequest.getServicePirce(sTypeId, versionType, callBack);
    }

    /**
     * 释放资源
     */
    public void release() {
        instance = null;
    }


    /**
     * @param brandId      品牌ID
     * @param appVersion   教辅云版本号
     * @param phoneVersion 手机型号
     * @param osVersion    操作系统版本号
     * @param netWorkType  用户网络
     * @param errorType    错误类型
     * @param logDesc      日志描述
     * @param remark       其他备注信息
     * @param callBack
     */
    public void addFeedbackLog(int brandId, String appVersion, String phoneVersion, String osVersion,
                               String netWorkType, int errorType, String logDesc, String remark,
                               final BaseCallBack callBack) {
        MeRequest.addFeedbackLog(brandId, appVersion, phoneVersion, osVersion, netWorkType, errorType, logDesc, remark, callBack);
    }

    /**
     * 获取用户积分等级信息
     */
    public void getUserInforDetail(BaseCallBack callBack) {
        MeRequest.getUserInforDatile(callBack);
    }

    /**
     * 获取用户积分等级信息
     *
     * @param userId 用户id
     */
    public void getUserPointRank(String userId, int bankId, BaseCallBack callBack) {
//        MeRequest.getUserPointRank(userId, bankId, callBack);
    }


    public void getUserPoint() {
//        try {
//            if (EApplication.getInstance()!=null
//                    &&EApplication.getInstance().getUserInfoBase()!=null){
//                long userId = EApplication.getInstance().getUserInfoBase().getUserId();
//                getUserPoint(userId+"");
//
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    /**
     * 获取用户积分（做作业积分有后台加积分，前台只需要获取提示一下）
     *
     * @param userId 用户id
     */
    public void getUserPoint(final String userId) {
        if (TextUtils.isEmpty(userId)) return;
        getUserPoint(userId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d("MeRequest", "获取积分失败:" + errorCode + ": " + data);
            }

            @Override
            public void failed(Object data) {
                CWLog.d("MeRequest", "获取积分失败:" + ": " + data);
            }

            public void success(Object data) {
                UserPointMedalsBean userPointMedalsBean = (UserPointMedalsBean) data;
                System.out.println("获取积分成功:" + ": " + userPointMedalsBean.toString());
                if (userPointMedalsBean != null) {
                    GetPointContral.handleUserPointMedals(EApplication.getInstance().getApplicationContext(), userPointMedalsBean);
                }
                //专为互动教程最为考试用书时接受此广播
                BaseApplication.getInstance().sendBroadcast(new Intent(EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER));
            }
        });
    }

    private long DALY_TIME = 1000;

    private void getUserPoint(final String userId, final BaseCallBack callBack) {
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MeRequest.getPoint(userId, callBack);
            }
        }, DALY_TIME);

    }

    private UserPointMedalsBean makeUserPointMedalsBean() {
        UserPointMedalsBean userPointMedalsBean = new UserPointMedalsBean();
        List<IntegralsBean> integrals = new ArrayList<>();
        List<MedalsBean> medals = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            IntegralsBean integralsBean = new IntegralsBean();
            integralsBean.setIntegral(1000 + i);
            integralsBean.setTypeName("提交作业添加积分" + i);
            integrals.add(integralsBean);

            MedalsBean medalsBean = new MedalsBean();
            medalsBean.setMedalName("十年寒窗Ⅰ级" + i);
            medalsBean.setMedalType("在习习向上提交自己的第1份作业" + i);
            medalsBean.setRemark("在习习向上提交自己的第1份作业" + i);
            medalsBean.setRarity(i);


            medals.add(medalsBean);
            medals.add(medalsBean);
        }
        userPointMedalsBean.setIntegrals(integrals);
        userPointMedalsBean.setMedals(medals);

        return userPointMedalsBean;

    }

    /**
     * 清零小红花
     *
     * @param userId   用户id数组
     * @param callBack 请求结果回调
     */
    public void deductdall(int[] userId, BaseCallBack callBack) {

        MeRequest.deductdall(userId, callBack);
    }

    /**
     * 为对应类型操作添加积分
     *
     * @param userId      用户id
     * @param userName    用户名
     * @param integralKey 操作类型（签到，做作业，分享）
     * @param objectId    对象ID(作业ID，学习记录ID，排行榜等)（可以为空）
     * @param callBack    请求结果回调
     */
    public void addPoint(String userId, String userName, String integralKey, String objectId, BaseCallBack callBack) {

        MeRequest.addPoint(userId, userName, integralKey, objectId, callBack);
    }

    public void addPoint(final String userId, String userName, final String integralKey, String objectId) {

        MeRequest.addPoint(userId, userName, integralKey, objectId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
//                UserPointMedalsBean userPointMedalsBean1 = makeUserPointMedalsBean();
//                GetPointContral.handleUserPointMedals(EApplication.getInstance().getApplicationContext(),userPointMedalsBean1);
//                System.out.println("添加积分失败:" + ": " + data.toString() + errorCode);
//                if (integralKey.equals(AddPointTypes.SHERE_SCORE) ||
//                        integralKey.equals(AddPointTypes.SHERE_RANK)||
//                        integralKey.equals(AddPointTypes.SHERE_FIRST_MEMORIZING_WORDS))
//                    ToastCustomView.getInstance().toastShowCenterSuccess(EApplication.getInstance().getResources().getString(R.string.share_success), Toast.LENGTH_SHORT);
                //专为互动教程最为考试用书时接受此广播
//                BaseApplication.getInstance().sendBroadcast(new Intent(EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER));
            }

            @Override
            public void failed(Object data) {
//                if (integralKey.equals(AddPointTypes.SHERE_SCORE) ||
//                        integralKey.equals(AddPointTypes.SHERE_RANK)||
//                integralKey.equals(AddPointTypes.SHERE_FIRST_MEMORIZING_WORDS))
                //专为互动教程最为考试用书时接受此广播
//                    BaseApplication.getInstance().sendBroadcast(new Intent(EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER));
            }

            public void success(Object string) {
//                System.out.println("添加积分成功:" + ": " + string);
//                UserPointMedalsBean userPointMedalsBean1 = makeUserPointMedalsBean();
//                GetPointContral.handleUserPointMedals(EApplication.getInstance().getApplicationContext(),userPointMedalsBean1);

//                afterAddPointSuccess(userId, integralKey, (String) string);

                //专为互动教程最为考试用书时接受此广播
//                BaseApplication.getInstance().sendBroadcast(new Intent(EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER));
            }

        });
    }

    private void afterAddPointSuccess(String userId, final String integralKey, final String integral) {
        getUserPoint(userId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                //从分享过来的，提示分享成功
                ToastCustomView.getInstance().toastShowCenterSuccess(EApplication.getInstance().getResources().getString(R.string.share_success), Toast.LENGTH_SHORT);
            }

            @Override
            public void failed(Object data) {
                //从分享过来的，提示分享成功
                ToastCustomView.getInstance().toastShowCenterSuccess(EApplication.getInstance().getResources().getString(R.string.share_success), Toast.LENGTH_SHORT);
            }

            public void success(Object data) {
                UserPointMedalsBean userPointMedalsBean = (UserPointMedalsBean) data;
                System.out.println("获取积分成功:" + ": " + userPointMedalsBean.toString());
                if (userPointMedalsBean != null) {
                    if ((userPointMedalsBean.getIntegrals() != null && userPointMedalsBean.getIntegrals().size() > 0)
                            || userPointMedalsBean.getMedals() != null && userPointMedalsBean.getMedals().size() > 0) {//获取积分又可以展示的数据
                        GetPointContral.handleUserPointMedals(EApplication.getInstance().getApplicationContext(), userPointMedalsBean);
                    } else {
                        CharSequence strToast = "积分成功";
                        if (integralKey.equals(AddPointTypes.SHERE_SCORE) ||
                                integralKey.equals(AddPointTypes.SHERE_RANK) ||
                                integralKey.equals(AddPointTypes.SHERE_FIRST_MEMORIZING_WORDS)) {

                            if ("0".equals(integral)) {
                                strToast = "分享成功";
                            } else {
                                strToast = "分享成功\n+" + integral + "积分";
                                SpannableString spannableString = new SpannableString(strToast);
                                ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#52CC8F"));
                                spannableString.setSpan(colorSpan, strToast.toString().indexOf("+"), strToast.toString().indexOf("+") + 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                strToast = spannableString;
                            }
                        }
                        ToastCustomView.getInstance().toastShowCenterSuccess(strToast, Toast.LENGTH_SHORT);

                    }
                }
                //专为互动教程最为考试用书时接受此广播
                BaseApplication.getInstance().sendBroadcast(new Intent(EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER));
            }
        });
    }

    /**
     * @param userId
     * @param rechargeNo
     * @param callBack
     */
    public void toRefPlayState(int userId, String rechargeNo, final BaseCallBack callBack) {
        MeRequest.toRefPlayState(userId, rechargeNo, callBack);
    }

    /**
     * 兑吧通用接口
     *
     * @param userId
     * @param redirect
     * @param callBack
     */
    public void getDuibaLogin(int userId, String redirect,
                              final BaseCallBack callBack) {
        MeRequest.getDuibaLogin(userId, redirect, callBack);
    }
}
